package org.bigdata.framework.core.protocol;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.bigdata.framework.core.elasticsearch.ESQueryBuilderConstructor;
import org.bigdata.framework.core.elasticsearch.ESQueryBuilders;
import org.bigdata.framework.core.elasticsearch.ElasticSearchService;
import org.bigdata.framework.core.model.Classes;
import org.bigdata.framework.core.model.CommonDataProperty;
import org.bigdata.framework.core.model.CommonObjectProperty;
import org.bigdata.framework.core.model.DataProperty;
import org.bigdata.framework.core.model.Dict;
import org.bigdata.framework.core.model.DictItem;
import org.bigdata.framework.core.model.ObjectProperty;
import org.bigdata.framework.core.model.SearchSortRule;
import org.bigdata.framework.core.model.SearchWeightCustoms;
import org.bigdata.framework.core.model.SearchWeightFields;
import org.bigdata.framework.core.model.ThesauriWord;
import org.bigdata.framework.core.model.ThesauriWordReference;
import org.bigdata.framework.core.service.IGeneralWordService;
import org.bigdata.framework.core.service.IThesauriWordReferenceService;
import org.bigdata.framework.core.service.IThesauriWordService;
import org.bigdata.framework.core.utils.LangDetectUtils;
import org.bigdata.framework.core.utils.MongoClientUtils;
import org.bigdata.framework.core.utils.MybatisPlusTools;
import org.bigdata.framework.core.utils.RedisUtils;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.plugins.Page;
import com.mongodb.client.MongoDatabase;
import com.xxl.conf.core.XxlConfClient;

/**
 * 搜索接口实现类
 * 
 * @author vimes 2016-10-31 11:18:45
 */
public class SearchService implements ISearchService {

	@Autowired
	private IGeneralWordService generalWordService;
	@Autowired
	private IThesauriWordService thesauriWordService;
	@Autowired
	private IThesauriWordReferenceService thesauriWordReferenceService;

	@Autowired
	private IPublicService publicService;
	@Autowired
	private IDynamicService dynamicService;
	
	RedisUtils aRedisUtils = new RedisUtils();

	// solr初始化
	//private static SolrClient server = new HttpSolrClient(XxlConfClient.get("dal.solr.storage.properties", "http://127.0.0.1:8983/solr/hymax"));
	private static SolrClient server = new HttpSolrClient.Builder(XxlConfClient.get("dal.solr.storage.properties", "http://127.0.0.1:8983/solr/hymax")).build();
	// 关键词solr核
//	private static SolrClient kwServer = new HttpSolrClient(XxlConfClient.get("dal.solr.keywords.properties", "http://10.215.4.12:8983/solr/keywords"));
	private static SolrClient kwServer = new HttpSolrClient.Builder(XxlConfClient.get("dal.solr.keywords.properties", "http://10.215.4.12:8983/solr/keywords")).build();
	// 词表solr核
//	private static SolrClient wordServer = new HttpSolrClient(XxlConfClient.get("dal.solr.word.properties","http://127.0.0.1:8983/solr/word"));
	private static SolrClient wordServer = new HttpSolrClient.Builder(XxlConfClient.get("dal.solr.word.properties","http://127.0.0.1:8983/solr/word")).build();
	// 百科solr核心
//	private static SolrClient baikeServer = new HttpSolrClient(XxlConfClient.get("dal.solr.baike.properties","http://127.0.0.1:8983/solr/baike"));
	private static SolrClient baikeServer = new HttpSolrClient.Builder(XxlConfClient.get("dal.solr.baike.properties","http://127.0.0.1:8983/solr/baike")).build();
	// 统计分析solr核心
//	private static SolrClient analysisServer = new HttpSolrClient(XxlConfClient.get("dal.solr.analysis.properties","http://127.0.0.1:8983/solr/analysis"));
	private static SolrClient analysisServer = new HttpSolrClient.Builder(XxlConfClient.get("dal.solr.analysis.properties","http://127.0.0.1:8983/solr/analysis")).build();
	// 标引api
//	private static SolrClient indexingServer = new HttpSolrClient("http://127.0.0.1:8983/solr/indexWeight");
	private static SolrClient indexingServer = new HttpSolrClient.Builder("http://127.0.0.1:8983/solr/indexWeight").build();

	//es集群名称
	private static String elasticsearchClusterName = XxlConfClient.get("dal.elasticsearch.cluster.name", "elasticsearch");
	//es服务器ip
	private static String elasticsearchHostIp = XxlConfClient.get("dal.elasticsearch.host.ip", "10.215.4.37");
	//es服务器端口
	private static String elasticsearchHostPort = XxlConfClient.get("dal.elasticsearch.host.port", "9300");
	//es连接
	ElasticSearchService aElasticSearchService = new ElasticSearchService(elasticsearchClusterName, elasticsearchHostIp, Integer.parseInt(elasticsearchHostPort));
	
	
	@Override
	public Long searchCount(String queryStr, String[] filterQueryStr) {
		// TODO Auto-generated method stub
		Long r = 0L;
		SolrQuery query = new SolrQuery();
		// 主查询
		//query.setQuery(replaceSolrQuery(queryStr));
		query.setQuery(toSolrQueryStr(queryStr));
		query.set("q.op", "AND");

		// 采用过滤器查询可以提高性能
		if (filterQueryStr != null) {
			for (int i = 0; i < filterQueryStr.length; i++) {
				filterQueryStr[i] = replaceSolrField(filterQueryStr[i]
						.split(":")[0])
						+ ":"
						+ ClientUtils.escapeQueryChars(filterQueryStr[i]
								.substring(filterQueryStr[i].split(":")[0]
										.length() + 1));
				System.out.println(filterQueryStr[i]);
				query.addFilterQuery(filterQueryStr[i]);
			}
		}

		QueryResponse response = null;
		try {
			response = server.query(query,METHOD.POST);
			SolrDocumentList docs = response.getResults();
			r = docs.getNumFound();
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return r;
	}

	@Override
	public HashMap<String, Object> search(String queryStr,
			String[] filterQueryStr, String[] highlightFields,
			String[] showFields, Object sortField,int sortRuleScope, boolean isOpenWeight,
			Map<String, String> solrBq, int pageNum, int pageSize) {

		// TODO Auto-generated method stub
		HashMap<String, Object> r = new HashMap<String, Object>();

		SolrQuery query = new SolrQuery();

		/**
		 * query.set("df", "title"); query.set("defType","edismax"); //
		 * qf对默认查询增加权重比值，比如标题是content的1.9倍，值越大权重越大 query.set("qf",
		 * "title^1 price^0.1"); query.setParam("q.op", "AND"); //
		 * sum(recip(ms(NOW
		 * ,pub_date),1,1,100),div(point,5632000),div(sale_count,1000000)) //
		 * bf用函数计算某个字段的权重，如上例子中pub_date发布日期的权重，point比如诚信指数，sale_count销售数量 //
		 * bf的函数查看solr api文档 http://wiki.apache.org/solr/FunctionQuery
		 * query.set("bf", "sum(abs(price))");
		 **/

		if (StringUtils.isNotBlank(queryStr) && !"*:*".equals(queryStr)) {
			// 是否开启权重查询
			if (isOpenWeight) {
				query.set("defType", "edismax");
				String classEn = getType(queryStr);
				Map<String, String> wfMap = new HashMap<String, String>();

				// 查询字段权重
				HashMap<String, Object> params = new HashMap<String, Object>();
				int classId = 0;
				if (StringUtils.isNotBlank(classEn)) {
					params.put("=,nameEn", classEn);
					List<Classes> classes = publicService.getClasses(params, 1,
							1);
					if (classes != null && classes.size() != 0) {
						params = new HashMap<String, Object>();
						classId = classes.get(0).getId();
						params.put("=,classesEn", classId);
						List<SearchWeightFields> privateWfs = publicService
								.getSearchWeightFields(params, 1, 1000);
						for (SearchWeightFields wf : privateWfs) {
							wfMap.put(wf.getNameEn(), wf.getHeightValue());
						}
					}
					params = new HashMap<String, Object>();
				}
				params.put("=,`range`", 0);
				List<SearchWeightFields> publicWfs = publicService
						.getSearchWeightFields(params, 1, 1000);
				for (SearchWeightFields wf : publicWfs) {
					// 如果私库已有该权重字段 那么舍弃全库相同的权重字段
					if (!wfMap.containsKey(wf.getNameEn())) {
						wfMap.put(wf.getNameEn(), wf.getHeightValue());
					}
				}
				if (wfMap.size() != 0) {
					query.setQuery(toWeightQueryStr(queryStr, wfMap));
				} else {
					query.setQuery(toSolrQueryStr(queryStr));
				}

				// 查询自定义权重值
				Map<String, String> wcMap = new HashMap<String, String>();
				if (classId != 0) {
					params = new HashMap<String, Object>();
					params.put("=,classesEn", classId);
					List<SearchWeightCustoms> privateWcs = publicService
							.getSearchWeightCustoms(params, 1, 1000);
					for (SearchWeightCustoms wc : privateWcs) {
						wcMap.put(wc.getNameEn(),
								wc.getFieldValue() + "`" + wc.getHeightValue());
					}
				}
				params = new HashMap<String, Object>();
				params.put("=,`range`", 0);
				List<SearchWeightCustoms> publicWcs = publicService
						.getSearchWeightCustoms(params, 1, 1000);
				for (SearchWeightCustoms wc : publicWcs) {
					// 如果私库已有该权重字段 那么舍弃全库相同的权重字段
					if (!wcMap.containsKey(wc.getNameEn())) {
						wcMap.put(wc.getNameEn(),
								wc.getFieldValue() + "`" + wc.getHeightValue());
					}
				}
				if (wcMap.size() != 0) {
					query.set("bq", toBqQuery(wcMap));
				}
			} else {
				query.setQuery(toSolrQueryStr(queryStr));
			}
			if (solrBq != null && solrBq.size() != 0) {
				if (!isOpenWeight) {
					query.set("defType", "edismax");
				}
				String customBq = toCustomBqQuery(solrBq);
				String bq = query.get("bq");
				if (StringUtils.isNotBlank(bq)) {
					customBq += bq;
				}
				query.set("bq", customBq);
			}
		} else {
			query.setQuery(queryStr);
		}

		//and查询条件
		query.set("q.op", "AND");

		if (showFields != null) {
			for (int i = 0; i < showFields.length; i++) {
				showFields[i] = replaceSolrField(showFields[i]);
			}
			query.setFields(showFields);
		}

		// 采用过滤器查询可以提高性能
		if (filterQueryStr != null) {
			for (int i = 0; i < filterQueryStr.length; i++) {
				//类似type:*特殊处理
				if(filterQueryStr[i].endsWith(":*")) {
					filterQueryStr[i] = replaceSolrField(filterQueryStr[i]
							.split(":")[0])
							+ ":"
							+ filterQueryStr[i]
									.substring(filterQueryStr[i].split(":")[0]
											.length() + 1);
				}else {
					filterQueryStr[i] = replaceSolrField(filterQueryStr[i]
							.split(":")[0])
							+ ":"
							+ ClientUtils.escapeQueryChars(filterQueryStr[i]
									.substring(filterQueryStr[i].split(":")[0]
											.length() + 1));
				}
				System.out.println(filterQueryStr[i]);
				query.addFilterQuery(filterQueryStr[i]);
			}
		}

		// 排序
		if (sortField != null) {
			if (sortField instanceof Map) {
				HashMap sort = (HashMap) sortField;
				Iterator iter = sort.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					Object key = entry.getKey();
					Object value = entry.getValue();
					if (value.toString().equals("desc")) {
						query.addSort(replaceSolrField(key.toString()),
								ORDER.desc);
					} else if (value.toString().equals("asc")) {
						query.addSort(replaceSolrField(key.toString()),
								ORDER.asc);
					}
				}
			} else {
				if (!isOpenWeight) {
					query.set("defType", "edismax");
				}
				String sort = sortField.toString();
				String[] sortArray = sort.split(":=:");
			   if(sortArray.length==2) {
				sort=sortArray[1];
				HashMap<String, Object> params = new HashMap<String, Object>();
				if(sortRuleScope == 1){
				//	String classEn = getType(queryStr);
					String classEn=sortArray[0];
					// 查询字段权重
					int classId = 0;
				
					if (StringUtils.isNotBlank(classEn)) {
						params.put("=,nameEn", classEn);
						List<Classes> classes = publicService.getClasses(params, 1,
								1);
						if (classes != null && classes.size() != 0) {
							params = new HashMap<String, Object>();
							classId = classes.get(0).getId();
							params.put("=,classesId", classId);
							params.put("=,nameEn", sort);
							List<SearchSortRule> sortRule = publicService
									.getSearchSortRule(params, 1, 1);
							if (sortRule != null && sortRule.size() != 0) {
								query.set("bf", getSolrFieldFromFunction(sortRule
										.get(0).getSortExpression()));
							} else {
								params = new HashMap<String, Object>();
								params.put("=,scope", 0);
								params.put("=,nameEn", sort);
								sortRule = publicService.getSearchSortRule(params,
										1, 1);
								if (sortRule != null && sortRule.size() != 0) {
									query.set("bf",
											getSolrFieldFromFunction(sortRule
													.get(0).getSortExpression()));
								}
							}
						}
					}
				}else{
					params.put("=,scope", 0);
					params.put("=,nameEn", sort);
					List<SearchSortRule> sortRule = publicService.getSearchSortRule(params,
							1, 1);
					if (sortRule != null && sortRule.size() != 0) {
						query.set("bf",
								getSolrFieldFromFunction(sortRule
										.get(0).getSortExpression()));
					}
				}
			}
		  }
		}
	//	query.set("bf", "product(recip(ms(NOW,dateIS_date),3.16e-11,35,1),12)^10000");
		// 标红
		if (highlightFields != null) {
			for (int i = 0; i < highlightFields.length; i++) {
				highlightFields[i] = replaceSolrField(highlightFields[i]);
			}
			query.set("hl.preserveMulti",true);
			query.setHighlight(true);
			query.setHighlightSimplePre("<span style='color:red'>");
			query.setHighlightSimplePost("</span>");
			query.setHighlightSnippets(1);
			query.setHighlightFragsize(1000);
			for (int i = 0; i < highlightFields.length; i++) {
				query.addHighlightField(highlightFields[i]);
			}
		}

		// 分页
		query.setStart((pageNum - 1) * pageSize);
		query.setRows(pageSize);
		QueryResponse response = null;
		try {
			response = server.query(query,METHOD.POST);
			SolrDocumentList docs = response.getResults();

			List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> mp = null;

			// 标红结果集
			Map<String, Map<String, List<String>>> highlightMap = response
					.getHighlighting();
			//System.out.println("highlightMap="+highlightMap);

			// 循环结果集
			for (int i = 0; i < docs.size(); i++) {
				mp = new HashMap<String, Object>();

				SolrDocument aSolrDocument = docs.get(i);
				Map<String, Collection<Object>> fieldValuesMap = aSolrDocument
						.getFieldValuesMap();
				// 索引ID
				String id = "";
				if (fieldValuesMap.get("id").size() > 0) {
					id = fieldValuesMap.get("id").iterator().next().toString();
				}
				
				for (int j = 0; j < showFields.length; j++) {
					Collection<Object> values = fieldValuesMap
							.get(showFields[j]);
					mp.put(replaceSolrField(showFields[j]), values);
				}
				if (highlightFields != null) {
					Map<String, List<String>> highlightValues = highlightMap
							.get(id);
					for (int k = 0; k < highlightFields.length; k++) {
						List<String> highlightList = highlightValues
								.get(highlightFields[k]);
						mp.put(replaceSolrField(highlightFields[k]) /*+ "_h"*/,
								highlightList);

					}
				}
				data.add(mp);
			}

			r.put("data", data);
			// 总数
			r.put("count", docs.getNumFound());
			// 响应时间
			r.put("time", response.getQTime()/1000.0);
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return r;
	}

	@Override
	public HashMap<String, Object> search(String queryStr,
			String[] filterQueryStr, String[] highlightFields,
			String[] showFields, Object sortField, int pageNum, int pageSize) {
		return search(queryStr, filterQueryStr, highlightFields, showFields,
				sortField,1, false, null, pageNum, pageSize);
	}

	@Override
	public HashMap<String, Object> search(String queryStr,
			String[] filterQueryStr, String[] highlightFields,
			String[] showFields, Object sortField, boolean isOpenWeight,
			int pageNum, int pageSize) {
		return search(queryStr, filterQueryStr, highlightFields, showFields,
				sortField,1, true, null, pageNum, pageSize);
	}

	public HashMap<String, Object> search(String queryStr,
			String[] filterQueryStr, String[] highlightFields,
			String[] showFields, Object sortField,int sortRuleScope,boolean isOpenWeight,
			int pageNum, int pageSize){
		return search(queryStr, filterQueryStr, highlightFields, showFields,
				sortField,sortRuleScope, true, null, pageNum, pageSize);
	}
	@Override
	public HashMap<String, Object> getDetail(String id, String[] showFields) {
		// TODO Auto-generated method stub
		HashMap<String, Object> r = new HashMap<String, Object>();

		SolrQuery query = new SolrQuery();

		// 主查询
		query.setQuery("id:" + id);

		if (showFields != null) {
			for (int i = 0; i < showFields.length; i++) {
				showFields[i] = replaceSolrField(showFields[i]);
			}
			query.setFields(showFields);
		}

		QueryResponse response = null;
		try {
			response = server.query(query,METHOD.POST);
			SolrDocumentList docs = response.getResults();

			List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> mp = null;

			// 循环结果集
			for (int i = 0; i < docs.size(); i++) {
				mp = new HashMap<String, Object>();

				SolrDocument aSolrDocument = docs.get(i);
				Map<String, Collection<Object>> fieldValuesMap = aSolrDocument
						.getFieldValuesMap();

				for (int j = 0; j < showFields.length; j++) {
					Collection<Object> values = fieldValuesMap
							.get(showFields[j]);
					mp.put(replaceSolrField(showFields[j]), values);
				}
				data.add(mp);
			}

			r.put("data", data);
			// 响应时间
			r.put("time", docs.getNumFound());
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return r;
	}

	/**
	 * 替换Solr表达式
	 * 
	 * @param queryStr
	 * @return
	 */
	private String replaceSolrQuery(String queryStr) {
		String r = queryStr;
		Pattern p = Pattern.compile("\\$(\\w+(\\d+)?):", Pattern.DOTALL);
		String res_str = r.replaceAll("AND|OR|NOT|\\(|\\)", "≡");
		String[] res_str_arr = res_str.split("≡");
		for (String x : res_str_arr) {
			Matcher ps_mac = p.matcher(x);
			if (ps_mac.find()) {
				String head = ps_mac.group(1);
				String head_str = replaceSolrField(head);
				String value_str = x.split(head)[1].substring(1);
				String newChar = head_str + ":"
						+ replaceSolrFieldValue(StringUtils.trim(head), StringUtils.trim(value_str));
				r = r.replace(StringUtils.trim(x), newChar);
			}

		}
		System.out.println(r);
		return r;
	}

	/**
	 * 替换字段
	 * 
	 * @param key
	 * @return
	 */
	private String replaceSolrField(String key) {
		if(key==null)
			return "";
		if (key.equals("id") || key.equals("type")) {
			return key;
		} else if (key.equals("stringIS_classEn")) {
			return "classEn";
		} else if (key.equals("dateIS_create_time")) {
			return "create_time";
		} else if (key.equals("create_time")) {
			return "dateIS_create_time";
		} else if (key.equals("stringIS_create_year")) {
			return "create_year";
		} else if (key.equals("create_year")) {
			return "stringIS_create_year";
		} else if (key.equals("dateIS_update_time")) {
			return "update_time";
		} else if (key.equals("update_time")) {
			return "dateIS_update_time";
		} else if (key.equals("classEn")) {
			return "stringIS_classEn";
		} else if (key.equals("stringIS_classZh")) {
			return "classZh";
		} else if (key.equals("classZh")) {
			return "stringIS_classZh";
		}else if (key.equals("intIS_create_user_id")) {
			return "create_user_id";
		}  else if (key.equals("create_user_id")) {
			return "intIS_create_user_id";
		} else if (key.equals("intIS_classes_id")) {
			return "classes_id";
		} else if (key.equals("classes_id")) {
			return "intIS_classes_id";
		} else if (key.equals("intIS_status")) {
			return "status";
		} else if (key.equals("status")) {
			return "intIS_status";
		} else if (key.startsWith("op_")) {
			return "stringIMS_" + key + "_data";
		} else if (key.startsWith("stringIMS_op_") && key.endsWith("_data")) {
			return key.replaceAll("stringIMS_", "").replaceAll("_data", "");
		} else {
			return (String) dynamicService.getDataSchema().get("field." + key);
		}
	}

	/**
	 * 替换字段值
	 * 
	 * @param value
	 * @return
	 */
	private String replaceSolrFieldValue(String field, String value) {
		if (replaceSolrField(field).startsWith("auto_")) {
			// ClientUtils.escapeQueryChars(value)
			return LangDetectUtils.detectLangAndWrap(value, true);
		} else {
			return value;
		}
	}

	@Override
	public HashMap<String, Object> searchGroup(String queryStr,
			String[] filterQueryStr, String[] groupFields,
			String[] groupQueryStr, int groupLimit) {

		return null;
	}

	@Override
	public HashMap<String, Object> searchFacet(String queryStr,
			String[] filterQueryStr, String[] facetFields, int limit) {
		// TODO Auto-generated method stub
		HashMap<String, Object> r = new LinkedHashMap<String, Object>();

		SolrQuery query = new SolrQuery();
		query.set("q.op", "AND");

		// 主查询
		//query.setQuery(replaceSolrQuery(queryStr));
		query.setQuery(toSolrQueryStr(queryStr));
		// query.setStart(0); // query的开始行数(分页使用)
		// query.setRows(100); // query的返回行数(分页使用)

		// 采用过滤器查询可以提高性能
		if (filterQueryStr != null) {
			for (int i = 0; i < filterQueryStr.length; i++) {
				filterQueryStr[i] = replaceSolrField(filterQueryStr[i]
						.split(":")[0])
						+ ":"
						+ ClientUtils.escapeQueryChars(filterQueryStr[i]
								.substring(filterQueryStr[i].split(":")[0]
										.length() + 1));
				System.out.println(filterQueryStr[i]);
				query.addFilterQuery(filterQueryStr[i]);
			}
		}

		for (int i = 0; i < facetFields.length; i++) {
			facetFields[i] = replaceSolrField(facetFields[i]);
		}

		// 分面
		query.setFacet(true);
		query.addFacetField(facetFields);
		query.setFacetLimit(limit); // 限制facet返回的数量
		query.setFacetMissing(false);// 不统计null的值
		query.setFacetMinCount(1);// 设置返回的数据中每个分组的数据最小值，比如设置为1，则统计数量最小为1，不然不显示

		QueryResponse response = null;
		try {
			response = server.query(query,METHOD.POST);
			List<FacetField> list = response.getFacetFields();
			for (int i = 0; i < list.size(); i++) {
				HashMap<String, Object> countMap = new LinkedHashMap<String, Object>();
				FacetField aFacetField = list.get(i);
				List<Count> countsList = aFacetField.getValues();
				for (int j = 0; j < countsList.size(); j++) {
					Count aCount = countsList.get(j);
					countMap.put(aCount.getName(), aCount.getCount());
				}
				r.put(replaceSolrField(aFacetField.getName()), countMap);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}

		return r;
	}

	@Override
	public HashMap<String, Object> searchBaikeFacet(String queryStr,
			String[] facetFields, int limit) {
		// TODO Auto-generated method stub
		HashMap<String, Object> r = new LinkedHashMap<String, Object>();

		SolrQuery query = new SolrQuery();

		// 主查询
		query.setQuery(queryStr);
		// query.setStart(0); // query的开始行数(分页使用)
		// query.setRows(100); // query的返回行数(分页使用)

		// 分面
		query.setFacet(true);
		query.addFacetField(facetFields);
		query.setFacetLimit(limit); // 限制facet返回的数量
		query.setFacetMissing(false);// 不统计null的值
		query.setFacetMinCount(1);// 设置返回的数据中每个分组的数据最小值，比如设置为1，则统计数量最小为1，不然不显示

		QueryResponse response = null;
		try {
			response = baikeServer.query(query);
			List<FacetField> list = response.getFacetFields();
			for (int i = 0; i < list.size(); i++) {
				HashMap<String, Object> countMap = new LinkedHashMap<String, Object>();
				FacetField aFacetField = list.get(i);
				List<Count> countsList = aFacetField.getValues();
				for (int j = 0; j < countsList.size(); j++) {
					Count aCount = countsList.get(j);
					countMap.put(aCount.getName(), aCount.getCount());
				}
				r.put(aFacetField.getName(), countMap);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		return r;
	}

	@Override
	public List<CommonDataProperty> getCommonDataPropertyListByCache() {
		// TODO Auto-generated method stub
		return (List<CommonDataProperty>) dynamicService.getDataSchema().get(
				"commonDpList");
		// return (List<CommonDataProperty>) redisService.getList(
		// ("commonDpList"), CommonDataProperty.class);
	}

	@Override
	public List<CommonObjectProperty> getCommonObjectPropertyListByCache() {
		// TODO Auto-generated method stub
		return (List<CommonObjectProperty>) dynamicService.getDataSchema().get(
				"commonOpList");
	}

	@Override
	public List<Classes> getClassesListByCache() {
		// TODO Auto-generated method stub
		return (List<Classes>) dynamicService.getDataSchema()
				.get("classesList");
	}

	@Override
	public List<DataProperty> getDataPropertyListCache(String classesEn) {
		// TODO Auto-generated method stub
		return (List<DataProperty>) dynamicService.getDataSchema().get(
				classesEn + ".dpList");
	}

	@Override
	public List<ObjectProperty> getObjectPropertyListCache(String classesEn) {
		// TODO Auto-generated method stub
		return (List<ObjectProperty>) dynamicService.getDataSchema().get(
				classesEn + ".opList");
	}

	// 拼接单值检索词
	private String getSearchWordValue(HashMap<String, Object> mp, String field) {
		String r = "";
		if (null == mp.get(field)) {
			return r;
		}
		List list = (List) mp.get(field);
		if (list.size() > 0) {
			r = (String) list.get(0);
		}
		return r;
	}

	@Override
	public List<String> getWordListByAutoComple(String word) {
		// TODO Auto-generated method stub
		List<String> r = new ArrayList<String>();
		HashMap<String, Object> data = searchKw("stringIS_word_chinese:("
				+ word + "*) OR stringIS_word_pingyin:(" + word
				+ "*) OR stringIS_word_pingyin_fl:(" + word
				+ "*) OR stringIS_word_english_lower:(" + word + "*)",
				new String[] { "stringIS_word_chinese" }, 1, 10);
		List<HashMap<String, Object>> dataList = (List<HashMap<String, Object>>) data
				.get("data");
		for (int i = 0; i < dataList.size(); i++) {
			HashMap<String, Object> mp = dataList.get(i);
			String wordName = "";
			if (!"".equals(getSearchWordValue(mp, "stringIS_word_chinese"))) {
				wordName = getSearchWordValue(mp, "stringIS_word_chinese");
			}
			r.add(wordName);
		}
		return r;
	}

	@Override
	public List<HashMap<String, Object>> getThesauriWordReference(String word) {
		// TODO Auto-generated method stub
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		HashMap<String, String> parmMap = new HashMap<String, String>();
		parmMap.put("name", word);
		HashMap<String, Object> map = null;

		// 搜索叙词表
		ThesauriWord aThesauriWord = null;
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,wordName", word);

		List<ThesauriWord> thesauriWordList = thesauriWordService.selectPage(
				new Page<ThesauriWord>(1, 1),
				new MybatisPlusTools<ThesauriWord>().getEwByList(queryParams))
				.getRecords();
		if (thesauriWordList.size() > 0) {
			aThesauriWord = thesauriWordList.get(0);
			HashMap<String, Object> trQueryParams = new HashMap<String, Object>();
			trQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
			List<ThesauriWordReference> list = thesauriWordReferenceService
					.selectPage(
							new Page<ThesauriWordReference>(1, 10),
							new MybatisPlusTools<ThesauriWordReference>()
									.getEwByList(trQueryParams)).getRecords();
			for (int i = 0; i < list.size(); i++) {
				ThesauriWordReference aThesauriWordReference = list.get(i);
				map = new HashMap<String, Object>();
				//
				ThesauriWord tThesauriWord = thesauriWordService
						.selectById(Integer.parseInt(aThesauriWordReference
								.getReferenceWordId()));
				map.put("name", tThesauriWord.getWordName());
				map.put("relationShip",
						aThesauriWordReference.getReferenceRelationLabel());
				r.add(map);
			}
		}
		return r;

	}

	@Override
	public List<Dict> getDictListByCache() {
		// TODO Auto-generated method stub
		return (List<Dict>) dynamicService.getDataSchema().get("dictList");
	}

	@Override
	public List<DictItem> getDictItemListByCache(String dictNameEn) {
		// TODO Auto-generated method stub
		return (List<DictItem>) dynamicService.getDataSchema().get(
				dictNameEn + ".dictItem");
	}

	@Override
	public Classes findClassesCache(String classesEn) {
		// TODO Auto-generated method stub
		return (Classes) dynamicService.getDataSchema().get(classesEn);
	}

	@Override
	public DataProperty findDataPropertyCache(String classesEn, String dpEn) {
		// TODO Auto-generated method stub
		return (DataProperty) dynamicService.getDataSchema().get(
				classesEn + ".dp." + dpEn);
	}

	@Override
	public ObjectProperty findObjectPropertyCache(String classesEn, String opEn) {
		// TODO Auto-generated method stub
		return (ObjectProperty) dynamicService.getDataSchema().get(
				classesEn + ".op." + opEn);
	}

	// 获取查询字符串中的type值
	Pattern typePattern = Pattern
			.compile("\\$type:(\\w+\\s*?)", Pattern.DOTALL);

	private String getType(String query) {
		Matcher match = typePattern.matcher(query);
		if (match.find()) {
			return match.group(1);
		}
		return null;
	}

	// 获取solr函数里的字段
	Pattern functionFieldPattern = Pattern.compile("\\$(\\w+\\s*?)\\$",
			Pattern.DOTALL);

	private String getSolrFieldFromFunction(String query) {
		Matcher match = functionFieldPattern.matcher(query);
		StringBuffer result = new StringBuffer();
		while (match.find()) {
			String newField = replaceSolrField(match.group(1));
			match.appendReplacement(result, newField);
		}
		return match.appendTail(result).toString();
	}

	/**
	 * 普通查询字符串转换成权重字符串
	 * 
	 * @param queryStr
	 *            普通字符串
	 * @param weightFieldsMap
	 *            权重值map key:权重字段 value:权重值
	 * @return 权重字符串 格式比如 title:张三^2 AND summary:张三^0.5
	 */
	Pattern fieldValuePattern = Pattern.compile(
			"\\s+(AND|OR|NOT)\\s+(\\(*\\s*)*\\$", Pattern.DOTALL);

	private String toWeightQueryStr(String queryStr,
			Map<String, String> weightFieldsMap) {
		String[] fieldValues = fieldValuePattern.split(queryStr);
		for (String fieldValue : fieldValues) {
			String[] fieldValueArray = fieldValue.trim().split(":", 2);
			String replaceNewField = fieldValueArray[0].indexOf("$") != -1 ? fieldValueArray[0]
					.substring(fieldValueArray[0].indexOf("$")) : "$"
					+ fieldValueArray[0];
			String newField = replaceSolrField(replaceNewField.substring(1));
			String replaceNewValue = fieldValueArray[1];
			if (replaceNewValue.trim().startsWith("(")) {
				replaceNewValue = replaceNewValue.substring(0,
						replaceNewValue.indexOf(")") + 1);
			} else if (replaceNewValue.trim().startsWith("\"")) {
				replaceNewValue = replaceNewValue.substring(0,
						replaceNewValue.lastIndexOf("\"") + 1);
			} else {
				replaceNewValue = replaceNewValue.replaceAll("\\)", "");
			}
			String newValue = toSolrFieldValue(newField, replaceNewValue.trim());
			if (weightFieldsMap != null
					&& weightFieldsMap
							.containsKey(replaceNewField.substring(1))) {
				newValue += "^"
						+ weightFieldsMap.get(replaceNewField.substring(1));
			}
			queryStr = queryStr.replace(
					replaceNewField + ":" + replaceNewValue.trim(), newField + ":"
							+ newValue.replace(":", "\\:"));
		}
		System.out.println(queryStr);
		return queryStr;
	}

	private String toSolrQueryStr(String queryStr) {

		return toWeightQueryStr(queryStr, null);
	}

	/**
	 * 增加某个具体值的权重
	 * 
	 * @param weightValuesMap
	 * @return 格式 如 title:张三^3 title:李四^2 summary:王五^10
	 */
	private String toBqQuery(Map<String, String> weightValuesMap) {
		StringBuffer result = new StringBuffer();
		Set<Entry<String, String>> entrySet = weightValuesMap.entrySet();
		for (Entry<String, String> entry : entrySet) {
			String newField = replaceSolrField(entry.getKey().trim());
			String[] valueWeights = entry.getValue().split("`");
			String[] values = valueWeights[0].split(";");
			for (String value : values) {
				result.append(newField).append(":").append("\"")
						.append(toSolrFieldValue(newField, value.trim()))
						.append("\"").append("^").append(valueWeights[1])
						.append(" ");
			}
		}
		return result.toString();
	}

	/**
	 * 增加自定义值权重
	 * 
	 * @param weightValuesMap
	 * @return
	 */
	private String toCustomBqQuery(Map<String, String> weightValuesMap) {
		StringBuffer result = new StringBuffer();
		Set<Entry<String, String>> entrySet = weightValuesMap.entrySet();
		for (Entry<String, String> entry : entrySet) {
			String[] field_value = entry.getKey().split(":");
			String newField = replaceSolrField(field_value[0].trim());
			String newValue = toSolrFieldValue(newField, field_value[1].trim());
			result.append(newField).append(":").append("\"").append(newValue)
					.append("\"").append("^").append(entry.getValue())
					.append(" ");
		}
		return result.toString();
	}

	private String toSolrFieldValue(String field, String value) {
		/*if (field.startsWith("auto_")) {
			if(value.startsWith("\"") && value.endsWith("\"")){
				return "\"" + LangDetectUtils.detectLangAndWrap(value.substring(1, value.length()-1), true) + "\"";
			}else if(value.startsWith("(") && value.endsWith(")")){
				return "(" +LangDetectUtils.detectLangAndWrap(value.substring(1,value.length()-1),true) +")";
			}else{
				return LangDetectUtils.detectLangAndWrap(value,true);
			}
		} else {
			return value;
		}
		*/
		return value;
	}

	@Override
	public Long searchKwCount(String queryStr) {
		// TODO Auto-generated method stub
		Long r = 0L;
		SolrQuery query = new SolrQuery();

		// 主查询
		query.setQuery(queryStr);

		QueryResponse response = null;
		try {
			response = kwServer.query(query);
			SolrDocumentList docs = response.getResults();
			r = docs.getNumFound();
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return r;
	}

	@Override
	public Long searchWordCount(String queryStr) {
		// TODO Auto-generated method stub
		Long r = 0L;
		SolrQuery query = new SolrQuery();

		// 主查询
		query.setQuery(queryStr);
		QueryResponse response = null;
		try {
			response = wordServer.query(query);
			SolrDocumentList docs = response.getResults();
			r = docs.getNumFound();
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return r;
	}

	@Override
	public Long searchBaikeCount(String queryStr) {
		// TODO Auto-generated method stub
		Long r = 0L;
		SolrQuery query = new SolrQuery();

		// 主查询
		query.setQuery(queryStr);
		QueryResponse response = null;
		try {
			response = baikeServer.query(query);
			SolrDocumentList docs = response.getResults();
			r = docs.getNumFound();
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return r;

	}

	@Override
	public HashMap<String, Object> searchKw(String queryStr,
			String[] showFields, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		HashMap<String, Object> r = new HashMap<String, Object>();

		SolrQuery query = new SolrQuery();
		query.setQuery(queryStr);

		if (showFields != null) {
			query.setFields(showFields);
		}

		// 分页
		query.setStart((pageNum - 1) * pageSize);
		query.setRows(pageSize);
		QueryResponse response = null;
		try {
			response = kwServer.query(query);
			SolrDocumentList docs = response.getResults();

			List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> mp = null;

			// 循环结果集
			for (int i = 0; i < docs.size(); i++) {
				mp = new HashMap<String, Object>();

				SolrDocument aSolrDocument = docs.get(i);
				Map<String, Collection<Object>> fieldValuesMap = aSolrDocument
						.getFieldValuesMap();
				for (int j = 0; j < showFields.length; j++) {
					Collection<Object> values = fieldValuesMap
							.get(showFields[j]);
					mp.put(showFields[j], values);
				}
				data.add(mp);
			}

			r.put("data", data);
			// 总数
			r.put("count", docs.getNumFound());
			// 响应时间
			r.put("time", docs.getNumFound());
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return r;
	}

	@Override
	public HashMap<String, Object> searchWord(String queryStr,
			String[] showFields, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		HashMap<String, Object> r = new HashMap<String, Object>();

		SolrQuery query = new SolrQuery();
		query.setQuery(queryStr);

		if (showFields != null) {
			query.setFields(showFields);
		}

		// 分页
		query.setStart((pageNum - 1) * pageSize);
		query.setRows(pageSize);
		QueryResponse response = null;
		try {
			response = wordServer.query(query);
			SolrDocumentList docs = response.getResults();

			List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> mp = null;

			// 循环结果集
			for (int i = 0; i < docs.size(); i++) {
				mp = new HashMap<String, Object>();

				SolrDocument aSolrDocument = docs.get(i);
				Map<String, Collection<Object>> fieldValuesMap = aSolrDocument
						.getFieldValuesMap();
				for (int j = 0; j < showFields.length; j++) {
					Collection<Object> values = fieldValuesMap
							.get(showFields[j]);
					mp.put(showFields[j], values);
				}
				data.add(mp);
			}

			r.put("data", data);
			// 总数
			r.put("count", docs.getNumFound());
			// 响应时间
			r.put("time", docs.getNumFound());
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return r;
	}

	@Override
	public HashMap<String, Object> searchBaike(String queryStr,
			String[] showFields, String[] highlightFields, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		HashMap<String, Object> r = new HashMap<String, Object>();

		SolrQuery query = new SolrQuery();
		query.setQuery(queryStr);

		if (showFields != null) {
			query.setFields(showFields);
		}
		
		// 标红
	    if (highlightFields != null) {
	      query.setHighlight(true);
	      query.setHighlightSimplePre("<span style='color:red'>");
	      query.setHighlightSimplePost("</span>");
	      query.setHighlightSnippets(1);
	      query.setHighlightFragsize(10000);
	      for (int i = 0; i < highlightFields.length; i++) {
	        query.addHighlightField(highlightFields[i]);
	      }
	    }

		// 分页
		query.setStart((pageNum - 1) * pageSize);
		query.setRows(pageSize);
		//query.addSort("stringIS_date", ORDER.desc);
		QueryResponse response = null;
		try {
			response = baikeServer.query(query);
			SolrDocumentList docs = response.getResults();

			List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> mp = null;
			
			// 标红结果集
		    Map<String, Map<String, List<String>>> highlightMap = response
		          .getHighlighting();

			// 循环结果集
			for (int i = 0; i < docs.size(); i++) {
				mp = new HashMap<String, Object>();

				SolrDocument aSolrDocument = docs.get(i);
				Map<String, Collection<Object>> fieldValuesMap = aSolrDocument
						.getFieldValuesMap();
				// 索引ID
		        String id = "";
		        if (fieldValuesMap.get("id").size() > 0) {
		          id = fieldValuesMap.get("id").iterator().next().toString();
		        }
		        if (highlightFields != null) {
		            Map<String, List<String>> highlightValues = highlightMap
		                .get(id);
		            for (int k = 0; k < highlightFields.length; k++) {
		              List<String> highlightList = highlightValues
		                  .get(highlightFields[k]);
		              mp.put(highlightFields[k] + "_h",
		                  highlightList);
		            }
		          }
				for (int j = 0; j < showFields.length; j++) {
					Collection<Object> values = fieldValuesMap
							.get(showFields[j]);
					mp.put(showFields[j], values);
				}
				data.add(mp);
			}

			r.put("data", data);
			// 总数
			r.put("count", docs.getNumFound());
			// 响应时间
			r.put("time", docs.getNumFound());
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return r;
	}
 

	@Override
	public Long searchIndexingCount(String queryStr, String[] filterQueryStr) throws Exception{
		Long r = 0L;
		SolrQuery query = new SolrQuery();

		// 主查询
		query.setQuery(queryStr);
		QueryResponse response = null;
//		try {
		response = indexingServer.query(query,METHOD.POST);
		SolrDocumentList docs = response.getResults();
		r = docs.getNumFound();
		/*} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}*/

		return r;
	}

	@Override
	public HashMap<String, Object> searchIndexing(String queryStr, int pageNum,
			int pageSize) {
		HashMap<String, Object> r = new HashMap<String, Object>();

		SolrQuery query = new SolrQuery();
		query.setQuery(queryStr);
		
		// 分页
		query.setStart((pageNum - 1) * pageSize);
		query.setRows(pageSize);
		QueryResponse response = null;
		try {
			response = indexingServer.query(query,METHOD.POST);
			SolrDocumentList docs = response.getResults();
			List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> mp = null;

			// 循环结果集
			for (int i = 0; i < docs.size(); i++) {
				mp = new HashMap<String, Object>();
				SolrDocument aSolrDocument = docs.get(i);
				Map<String, Collection<Object>> fieldValuesMap = aSolrDocument.getFieldValuesMap();
				mp.put("id", fieldValuesMap.get("id"));
				mp.put("title", fieldValuesMap.get("auto_stringITSV_title"));
				mp.put("keyword", fieldValuesMap.get("stringIMS_keyword"));
				mp.put("summary", fieldValuesMap.get("auto_stringITSV_summary"));
				mp.put("text", fieldValuesMap.get("auto_stringITSV_text"));
				mp.put("extend1", fieldValuesMap.get("auto_stringITSV_extend1"));
				mp.put("extend2", fieldValuesMap.get("auto_stringITSV_extend2"));
				mp.put("extend3", fieldValuesMap.get("auto_stringITSV_extend3"));
				data.add(mp);
			}
			r.put("data", data);
			// 总数
			r.put("count", docs.getNumFound());
			// 响应时间
			r.put("time", docs.getNumFound());
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return r;
	}
	
	@Override
	public Map<Object, Object> esStatSearch(Map<String, Object> conditions,String index, String type, int size, String field) {
		ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
		ESQueryBuilders aESQueryBuilders = null;
		if (conditions != null) {
			aESQueryBuilders = new ESQueryBuilders();
			Iterator iter = conditions.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = entry.getKey().toString();
				String value = entry.getValue().toString();
				if (key.toString().startsWith("=")) {
					if(!field.endsWith("date")){
						aESQueryBuilders.term(key.substring(1) +".keyword", value);
					}else{
						aESQueryBuilders.term(key.substring(1) + "", value);
					}
					
				} else if (key.toString().startsWith("><")) {
					if(!field.endsWith("date")){
						aESQueryBuilders.range(key.substring(2) + ".keyword", value.split("#")[0], value.split("#")[1]);
					}else{
						aESQueryBuilders.range(key.substring(2) + "", value.split("#")[0], value.split("#")[1]);
					}
					
				} else {
					aESQueryBuilders.match(key, value);
				}
			}
		}
		constructor.must(aESQueryBuilders);
		if(!field.endsWith("date")){
			field=field+".keyword";
		}
		AggregationBuilder agg = AggregationBuilders.terms("agg").field(field).size(size);
		return aElasticSearchService.statSearch(index, type, constructor, agg);
	}

	
	@Override
	public Map<String, Object> esStatSearch(Map<String, Object> conditions,String index, String type, int size, String field,String condition) {
		ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
		ESQueryBuilders aESQueryBuilders = null;
		if (conditions != null) {
			aESQueryBuilders = new ESQueryBuilders();
			Iterator iter = conditions.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = entry.getKey().toString();
				String value = entry.getValue().toString();
				if (key.toString().startsWith("=")) {
					if(!field.endsWith("date")){
						aESQueryBuilders.term(key.substring(1), value);
					}else{
						aESQueryBuilders.term(key.substring(1) + "", value);
					}
					
				} else if (key.toString().startsWith("><")) {
					if(!field.endsWith("date")){
						aESQueryBuilders.range(key.substring(2), value.split("#")[0], value.split("#")[1]);
					}else{
						aESQueryBuilders.range(key.substring(2) + "", value.split("#")[0], value.split("#")[1]);
					}
					
				} else {
					aESQueryBuilders.match(key, value);
				}
			}
		}
		constructor.must(aESQueryBuilders);
		if(!field.endsWith("date")){
			field=field+".keyword";
		}
		AggregationBuilder agg = AggregationBuilders.terms("agg").field(field).order(Terms.Order.term(true)).size(size);
		return aElasticSearchService.statSearch(index, type, constructor, agg,condition);
	}

	@Override
	public Long esSearchCount(Map<String, Object> conditions, String index, String type) {
		ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
		ESQueryBuilders aESQueryBuilders = null;
		if (conditions != null) {
			aESQueryBuilders = new ESQueryBuilders();
			Iterator iter = conditions.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = entry.getKey().toString();
				String value = entry.getValue().toString();
				if (key.toString().startsWith("=")) {
					aESQueryBuilders.term(key.substring(1) + ".keyword", value);
				} else if (key.toString().startsWith("><")) {
					aESQueryBuilders.range(key.substring(2) + ".keyword", value.split("#")[0], value.split("#")[1]);
				} else {
					aESQueryBuilders.match(key, value);
				}
			}
		}
		constructor.must(aESQueryBuilders);
		return aElasticSearchService.searchCount(index, type, constructor);
	}
	
	@Override
	public List<Map<String, Object>> esSearch(Map<String, Object> conditions, String index, String type,List<String>field,int pageNumber,int pageSize) {
		ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
		ESQueryBuilders aESQueryBuilders = null;
		if (conditions != null) {
			aESQueryBuilders = new ESQueryBuilders();
			Iterator iter = conditions.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = entry.getKey().toString();
				String value = entry.getValue().toString();
				if (key.toString().startsWith("=")) {
					aESQueryBuilders.term(key.substring(1) + ".keyword", value);
				} else if (key.toString().startsWith("><")) {
					aESQueryBuilders.range(key.substring(2) + ".keyword", value.split("#")[0], value.split("#")[1]);
				} else {
					aESQueryBuilders.match(key, value);
				}
			}
		}
		constructor.must(aESQueryBuilders);
		constructor.setDesc("create_time.keyword");
		constructor.setFrom((pageNumber-1)*pageSize); // 分页查询条目起始位置， 默认0
		constructor.setSize(pageSize); // 查询返回条数，最大 10000
		return aElasticSearchService.search(index, type, constructor);
	}
	
	@Override
	public  List<String> sortValue(String index, String type, int size, String field,String describe) {
		ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
		constructor.setSize(size);
		 if("desc".equals(describe.toLowerCase())){
			 constructor.setDesc(describe); 
		 }
		 if("asc".equals(describe.toLowerCase())){
			 constructor.setAsc(describe);; 
		}
		return aElasticSearchService.sortValue(index,type,constructor,field);
	}
	/**
	 * 
	* method: getSumForColumnName
	* Description:根据条件分组获取价格数据的和
	* @author 邢天龙
	* @date 2018年4月13日 上午9:24:25
	* @version 1.0
	 */
	@Override
	public List<Map<String,Object>> getSumForColumnName(String index, String type, String groupByColumn, String sumColumn,Map<String,Object> map ){
		ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
		ESQueryBuilders  aESQueryBuilders = new ESQueryBuilders();
		if (null!=map&&map.size()>0) {
			Iterator iter = map.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = entry.getKey().toString();
				String value = entry.getValue().toString();
				aESQueryBuilders.term(key, value);
			}
		}
		constructor.must(aESQueryBuilders);
		List<Map<String,Object>> result=aElasticSearchService.getSumForColumnName(index,type,constructor,groupByColumn,sumColumn);
		if(result.size()==0){//查询不到值则赋值为0
		  String []names={"机构用户","个人用户"}; 	
		  for(String name:names){
			  Map<String,Object> dataMap=new HashMap(); 
			  dataMap.put("name",name);
			  dataMap.put("value",0);
			  result.add(dataMap);
		  }
		 
		}
		if(result.size()==1){//缺少一个类型补全
			  Map<String,Object> dataMap=new HashMap(); 
			  Map<String,Object>data=result.get(0);
			   String name=data.get("name").toString();				   
				  if("机构用户".equals(name)){
					  dataMap.put("name","个人用户");
					  dataMap.put("value",0);
				  }
				  if("个人用户".equals(name)){
					  dataMap.put("name","机构用户");
					  dataMap.put("value",0);
				  }
				  result.add(dataMap);
			}
 		      return result;
	}
     /**
      * 根据时间查询计算热词的百分比
      */
	@Override
	public Map<String, Object> getHotWordsPercentage(String index, String type,int size,Map<String,Object> conditions,String field) {
		ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
		ESQueryBuilders aESQueryBuilders = new ESQueryBuilders();
	    Map<String,Object> result = new LinkedHashMap<String,Object>();
		if (conditions != null) {
			aESQueryBuilders = new ESQueryBuilders();
			Iterator iter = conditions.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = entry.getKey().toString();
				String value = entry.getValue().toString();
				if (key.toString().startsWith("=")) {
					if(!field.endsWith("date")){
						aESQueryBuilders.term(key.substring(1), value);
					}else{
						aESQueryBuilders.term(key.substring(1) + "", value);
					}
					
				} else if (key.toString().startsWith("><")) {
					if(!field.endsWith("date")){
						aESQueryBuilders.range(key.substring(2), value.split("#")[0], value.split("#")[1]);
					}else{
						aESQueryBuilders.range(key.substring(2) + "", value.split("#")[0], value.split("#")[1]);
					}
					
				} else {
					aESQueryBuilders.match(key, value);
				}
			}
		}
		constructor.must(aESQueryBuilders);
		if(!field.endsWith("date")){
			field=field+".keyword";
		}
		AggregationBuilder agg = AggregationBuilders.terms("agg").field(field).size(size);
		Map<Object, Object> statSearch = aElasticSearchService.statSearch(index, type, constructor, agg);
		Long searchCountIsNotNull = aElasticSearchService.searchCountIsNotNull(index, type, constructor,field);
		Iterator<Entry<Object, Object>> iterator = statSearch.entrySet().iterator();
		if(searchCountIsNotNull>0){
	     while(iterator.hasNext()){
	        Map.Entry entry = (Map.Entry) iterator.next();
	        String key= entry.getKey().toString();
	        String value= entry.getValue().toString();
	        DecimalFormat    format   = new DecimalFormat("######0.00");
	        double doubleValue = Double.parseDouble(value);
			String percentage=format.format((doubleValue/(double)searchCountIsNotNull)*100);
		    if(percentage.endsWith(".0")){
			 percentage=percentage.replace(".0", "");
		   }
	    	result.put(key, "0".equals(percentage)?"0":percentage+"%"+"=="+value);

	      }
		}
		    return result;
	}
		public Long getVisitorsNumber(Map<String, Object> conditions, String index, String type) {
			ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
			ESQueryBuilders aESQueryBuilders = new ESQueryBuilders();
			if (conditions != null) {
				aESQueryBuilders = new ESQueryBuilders();
				Iterator iter = conditions.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String key = entry.getKey().toString();
					String value = entry.getValue().toString();
					if (key.toString().startsWith("=")) {
						aESQueryBuilders.term(key.substring(1) + "", value);
					}else if (key.toString().startsWith("><")) {
					  aESQueryBuilders.range(key.substring(2), value.split("#")[0], value.split("#")[1]);
					} else {
						aESQueryBuilders.match(key, value);
					}
				}
			}
			constructor.must(aESQueryBuilders);
			return aElasticSearchService.searchCount(index, type, constructor);
		}

}
